package com.milhouz.findmydroid;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.milhouz.findmydroid.bean.Character;
import com.milhouz.findmydroid.bean.Game;
import com.milhouz.findmydroid.bean.Team;
import com.milhouz.findmydroid.db.AppConstants;
import com.milhouz.findmydroid.db.AppDbAPI;
import com.milhouz.findmydroid.exception.EndOfCharacterListException;
import com.milhouz.findmydroid.exception.EndOfGameException;
import com.milhouz.findmydroid.util.StringUtils;
import com.milhouz.findmydroid.view.CountDown;

public class FindMyDroidGameActivity extends Activity {

	// Game Settings bean
	private static Game mGame;
	// CountDown
	private static CountDown mCountdown;
	// Views
	private static TextView mTeam;
	private static ProgressBar mTimer;
	private static TextView mCategory;
	private static TextView mNbCard;
	private static TextView mGameTypeLabel;
	private static TextView mCharacters;
	// Buttons
	private static Button mFoundButton;
	private static Button mNextButton;
	private static Button mFaultButton;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// Set window content (with fullscreen mode)
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setContentView(R.layout.game);

		// Game Settings
		mGame = getIntent().getExtras().getParcelable(getString(R.string.intent_extra_game));
		mGame.initGame();

		Log.i(AppConstants.TAG, ">>> " + mGame.getCharacters().size());

		// Get game characters
		AppDbAPI.getInstance().getRandomCharacters(getApplicationContext(), mGame);

		// Get views
		mTeam = (TextView) findViewById(R.id.team);
		mTimer = (ProgressBar) findViewById(R.id.timer);
		mCategory = (TextView) findViewById(R.id.category);
		mNbCard = (TextView) findViewById(R.id.nbCard);
		mGameTypeLabel = (TextView) findViewById(R.id.gameTypeLabel);
		mCharacters = (TextView) findViewById(R.id.characters);

		// Get buttons
		mFoundButton = (Button) findViewById(R.id.foundButton);
		mNextButton = (Button) findViewById(R.id.nextButton);
		mFaultButton = (Button) findViewById(R.id.faultButton);

		// Add buttons listeners
		mFaultButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				mCountdown.cancel();
				showNextTeamDialog(false);
			}
		});
		mNextButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				// go to next game step
				nextGameStep();
			}
		});

		mFoundButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				// update score (add point)
				mGame.getCurrentTeam().addPoint();
				updateTeamViews(mGame.getCurrentTeam());
				// go to next game step
				nextGameStep();
			}
		});

		// Update views
		updateGameViews();
		updateTeamViews(mGame.getCurrentTeam());
		updateCharacterViews(mGame.getCurrentCharacter());

		// Show dialog
		showPhaseGameDialog(true);
	}

	/** Start a countdown */
	private void startCountDown() {
		mCountdown = new CountDown(mTimer, mGame.getTime() * 1000) {
			@Override
			public void onFinishCountdown() {
				showNextTeamDialog(true);
			}
		};
		mCountdown.start();
	}

	/** Update the character view */
	private void updateCharacterViews(final Character character) {
		String categoryName = AppDbAPI.getInstance().getCategoryName(this, character.getCategoryId());
		mCategory.setText(getString(R.string.category_view, categoryName));
		mNbCard.setText((mGame.getCurrentCharacterId() + 1) + "/" + mGame.getNbCards());
		mCharacters.setText(character.getName());
	}

	/** Update the team view */
	private void updateTeamViews(final Team team) {
		mTeam.setText(StringUtils.displayTeamScore(this, team));
	}

	/** Update the game view */
	private void updateGameViews() {
		switch (mGame.getGameMode()) {
		case DESCRIBE_MODE:
			mGameTypeLabel.setText(getString(R.string.rules_describe_view));
			break;
		case ONEWORD_MODE:
			mGameTypeLabel.setText(getString(R.string.rules_oneword_view));
			break;
		case MIME_MODE:
			mGameTypeLabel.setText(getString(R.string.rules_mime_view));
			break;
		}
	}

	/** Update game to the next step */
	private void nextGameStep() {
		try {
			updateCharacterViews(mGame.getNextCharacter());
		} catch (EndOfCharacterListException e) {
			// End of game card
			try {
				mCountdown.cancel();
				// Next game mode
				mGame.setNextGameMode();
				updateGameViews();
				// Update new game mode characters
				mGame.shuffleCharacters();
				updateCharacterViews(mGame.getCurrentCharacter());
				// Show dialog
				showPhaseGameDialog(false);
			} catch (EndOfGameException e1) {
				// End of game
				showEndOfGameDialog();
			}
		}
	}

	// TODO Mutualiser les boites de dialog
	/** Show next team dialog */
	private void showNextTeamDialog(boolean onFinishCountdown) {
		AlertDialog.Builder builder = new AlertDialog.Builder(FindMyDroidGameActivity.this);
		if (onFinishCountdown) {
			builder.setTitle(getString(R.string.dialog_nextteam_title1));
		} else {
			builder.setTitle(getString(R.string.dialog_nextteam_title1));
		}
		builder.setMessage(getString(R.string.dialog_nextteam_message));
		builder.setPositiveButton(getString(R.string.dialog_play), new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface arg0, int arg1) {
				updateTeamViews(mGame.getNextTeam());
				startCountDown();
			}
		});
		if (!onFinishCountdown) {
			builder.setNegativeButton(getString(R.string.dialog_cancel), new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface arg0, int arg1) {
					mCountdown.start();
				}
			});
		}
		builder.create().show();
	}

	/** Show next game dialog */
	private void showPhaseGameDialog(boolean firstPhase) {
		AlertDialog.Builder builder = new AlertDialog.Builder(FindMyDroidGameActivity.this);
		if (firstPhase) {
			builder.setTitle(getString(R.string.dialog_nextphase_title1));
			mNextButton.setVisibility(View.GONE);
		} else {
			builder.setTitle(getString(R.string.dialog_nextphase_title2));
			mNextButton.setVisibility(View.VISIBLE);
		}
		builder.setMessage(StringUtils.displayGameMode(this, mGame.getGameMode()));
		builder.setPositiveButton(getString(R.string.dialog_nextphase_message, mGame.getCurrentTeam().getTeamNumber()) //
				, new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface arg0, int arg1) {
						startCountDown();
					}
				});
		builder.create().show();
	}

	/** Show end of game dialog */
	private void showEndOfGameDialog() {
		mCountdown.cancel();
		AlertDialog.Builder builder = new AlertDialog.Builder(FindMyDroidGameActivity.this);
		builder.setTitle(getString(R.string.dialog_enddialog_title));
		builder.setMessage(getString(R.string.dialog_enddialog_title, mGame.getWinner().getTeamNumber(), StringUtils.displayTeamsScore(this, mGame.getTeams())));
		builder.setPositiveButton(getString(R.string.dialog_return), new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface arg0, int arg1) {
				FindMyDroidGameActivity.this.finish();
			}
		});
		builder.create().show();
	}

	/** Show pause dialog */
	private void showPauseDialog() {
		mCountdown.cancel();
		AlertDialog.Builder builder = new AlertDialog.Builder(FindMyDroidGameActivity.this);
		builder.setTitle(getString(R.string.dialog_pause_title));
		builder.setMessage(StringUtils.displayTeamsScore(this, mGame.getTeams()));
		builder.setPositiveButton(getString(R.string.dialog_resume), new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface arg0, int arg1) {
				mCountdown.start();
			}
		});
		builder.setNegativeButton(getString(R.string.dialog_quit), new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface arg0, int arg1) {
				FindMyDroidGameActivity.this.finish();
			}
		});
		builder.create().show();
	}

	@Override
	public void onBackPressed() {
		showPauseDialog();
	}

}
